<?php
class GoodsController extends BaseController
{   

    public function _initialize() {
        parent::_initialize();
        $this->id = session('id');
    }
    public function index()
    {   
        $type = isset($_GET['type']) ? $_GET['type'] : 2;
        $user_info = M('user')->where(['id'=>$this->id])->field('id,username,real_name,nickname,balance,upvaluation')->find();
        $goods_info = M('goods')->where(['cat_ids'=>$type,'status'=>1])->order('id desc')->select();
        include template('/user/goods/index');
    }

    //兑换
    public function duihuan_goods(){
        if(IS_POST){
            $id = $_POST['id'];
            $user_info = M('user')->where(['id'=>$this->id])->field('id,upvaluation,freeze_upvaluation,username')->find();
            $goods_info = M('goods')->where(['id'=>$id])->find();
            if($user_info['upvaluation'] < $goods_info['price']) showmessage('升值链不足'.$goods_info['price']);
            $data = [
                'upvaluation'=>($user_info['upvaluation'] - $goods_info['price']) ? ($user_info['upvaluation'] - $goods_info['price']) : 0,
                'freeze_upvaluation' => $user_info['freeze_upvaluation'] + $goods_info['price']
            ];
            $data1 = [
                'user_id'=>$this->id,
                'goods_id'=>$id,
                'price'=>$goods_info['price'],
                'status'=>1,
                'type'=>$goods_info['cat_ids'],
                'add_time'=>date('Y-m-d H:i:s'),
                'update_time'=>date('Y-m-d H:i:s'),
                'goods_remarks'=>'兑换'.$goods_info['name'].'消耗'.$goods_info['price'].'GF',
                'username'=>$user_info['username'],
            ];
            $data2 = [
                'user_id'=>$this->id,
                'balance'=>$goods_info['price'],
                'type'=>2,
                'add_time'=>date('Y-m-d H:i:s'),
                'remarks'=>'兑换商城商品'
            ];
            try{
                M('user')->where(['id'=>$this->id])->save($data);
                M('goods_buy_records')->add($data1);
                M('upvaluation_exchange_records')->add($data2);
            }catch(\Exception $e){
                showmessage($e->getMessage());
            }
            showmessage('操作成功','goback',1);
        }else{
            showmessage('非法访问');
        }
    }

    //记录
    public function records()
    {   
        $records = M('goods_buy_records')->where(['user_id'=>$this->id])->select();
        include template('/user/goods/records');
    }

    //详情
    public function records_detail(){
        $info = M('goods_buy_records')->where(['id'=>$_GET['id']])->find();
        include template('/user/goods/records_detail');
    }


    //商品详情
    public function goods_detail(){
        $id = $_GET['id'];
        $info = M('goods')->where(['id'=>$id])->find();
        include template('/user/goods/goods_detail');
    }
}